<?php

// 任务类

namespace Service;
use SmileYi\Utils\Log;
use SmileYi\Utils\Config;

class Task {

	private $redis;
	private $tasks = [];

	const TASK_LIST_KEY = 'deplay_task_list';

	function __construct(){
		$this->redis = new Redis('127.0.0.1');
		$this->tasks = Config::get('app.tasks');
	}

	/**
	 * 添加任务
	 * @param 	$name
	 * @return 	boolean
	 */
	function add($name){
		$task = json_encode([
			'name' => $name,
			'datetime' => date('Y-m-d H:i:s')
		]);
		$this->redis->rpush(self::TASK_LIST_KEY, $task);
		return true;
	}

	/**
	 * 弹出任务
	 * @return name
	 */
	function pop(){
		$task = $this->redis->lpop(self::TASK_LIST_KEY);
		if (!$task) {
			return null;
		} else {
			return json_decode($task, true);
		}
	}

	/**
	 * 执行任务
	 * @param   $task 
	 * @return  boolean [<description>]
	 */
	function run($task){
		set_time_limit(0);

		if (!isset($task['name']) || !isset($this->tasks[$task['name']])) {
			return false;
		}

		$task = array_merge($task, $this->tasks[$task['name']]);
		$shell = sprintf('cd %s && ./%s > shell.log', $task['dir'], $task['shell']);

		exec($shell, $output, $exit);

		Log::getInstanct()->put('exec', [
			'task' => $task,
			'exit' => $exit,
			'output' => $output
		]);

		if ($exit == 0) {
			return true;
		}
		
		return false;
	}
}